﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using CSharpTest.Net.Crypto;
using System.Security.Cryptography;
using System.IO;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using System.Xml;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;

namespace SmartVault.Core
{
    /// <summary>
    /// RSAPublicKey2
    /// 
    /// Extends RSAPublicKey2 to introduce the ability to work with PEM files.
    ///
    /// This functionality should be ported back into CSharpTest.Net
    /// </summary>
    public class RSAPublicKey2 : RSAPublicKey
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="provider"></param>
        public RSAPublicKey2(RSACryptoServiceProvider provider)
            : base(provider)
        {

        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="parameters"></param>
        public RSAPublicKey2(RSAParameters parameters)
            : base(parameters)
        {

        }

        /// <summary>
        /// Reads a public key from XML
        /// </summary>
        /// <param name="xrdr"></param>
        /// <returns></returns>
        public new static RSAPublicKey2 FromXml(XmlReader xrdr)
        {
            RSAParameters param = new RSAParameters();
            while (xrdr.Read())
            {
                if (xrdr.NodeType == XmlNodeType.Element)
                {
                    if (xrdr.LocalName == "Modulus") param.Modulus = Convert.FromBase64String(xrdr.ReadElementString());
                    if (xrdr.LocalName == "Exponent") param.Exponent = Convert.FromBase64String(xrdr.ReadElementString());
                }
            }
            Check.Assert<FormatException>(param.Modulus != null && param.Exponent != null);
            return new RSAPublicKey2(param);
        }

        /// <summary>
        /// Reads a public key from XML.
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public new static RSAPublicKey2 FromXml(string xml)
        {
            using (StringReader str = new StringReader(xml))
            {
                using (XmlTextReader rdr = new XmlTextReader(str))
                {
                    return FromXml(rdr);
                }
            }
        }

        /// <summary>
        /// Reads an RSAKeyPair from PEM. Can handle public keys, certificates, etc.
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static RSAKeyPair FromPEM(string xml)
        {
            using (StringReader str = new StringReader(xml))
            {
                return ReadPEM(str);
            }
        }

        /// <summary>
        /// Reads an RSAKeyPair from PEM. Can handle public keys, certificates, etc.
        /// </summary>
        /// <param name="rdr"></param>
        /// <returns></returns>
        public static RSAKeyPair ReadPEM(TextReader rdr)
        {
            var x = new PemReader(rdr);
            var y = x.ReadObject();
            RsaKeyParameters pub = null;
            RsaPrivateCrtKeyParameters pri = null;

            if (y.GetType().Equals(typeof(AsymmetricCipherKeyPair)))
            {
                AsymmetricCipherKeyPair k = y as AsymmetricCipherKeyPair;
                pub = k.Public as RsaKeyParameters;
                pri = k.Private as RsaPrivateCrtKeyParameters;
            }
            if (y.GetType().Equals(typeof(RsaKeyParameters)))
            {
                pub = y as RsaKeyParameters;
            }
            else if (y.GetType().Equals(typeof(X509Certificate)))
            {
                X509Certificate cert = (X509Certificate)y;
                pub = PublicKeyFactory.CreateKey(cert.CertificateStructure.SubjectPublicKeyInfo) as RsaKeyParameters;
            }

            RSACryptoServiceProvider pubProvider = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create();
            var puba = new RSAParameters();
            puba.Modulus = pub.Modulus.ToByteArrayUnsigned();
            puba.Exponent = pub.Exponent.ToByteArrayUnsigned();
            pubProvider.ImportParameters(puba);

            RSAPublicKey2 pubKey = new RSAPublicKey2(puba);

            RSAPrivateKey2 privateKey = null;

            if (pri != null)
            {
                RSACryptoServiceProvider priProvider = (RSACryptoServiceProvider) RSACryptoServiceProvider.Create();
                var pria = new RSAParameters();

                // private exponent
                pria.D = pri.Exponent.ToByteArrayUnsigned();

                // exponent1
                pria.DP = pri.DP.ToByteArrayUnsigned();
                
                // exponent2
                pria.DQ = pri.DQ.ToByteArrayUnsigned();

                // e, the public exponent
                pria.Exponent = pri.PublicExponent.ToByteArrayUnsigned();
               
                // coefficent
                pria.InverseQ = pri.QInv.ToByteArrayUnsigned();

                // n, modulus
                pria.Modulus = pri.Modulus.ToByteArrayUnsigned();

                // prime1
                pria.P = pri.P.ToByteArrayUnsigned();
                
                // prime2
                pria.Q = pri.Q.ToByteArrayUnsigned();

                privateKey = new RSAPrivateKey2(pria);
            }

            return new RSAKeyPair(pubKey, privateKey);
        }

        /// <summary>
        /// Writes the public key to PEM format
        /// </summary>
        /// <returns></returns>
        public string ToPEM()
        {
            using (StringWriter w = new StringWriter())
            {
                WritePEM(w);
                return w.ToString();
            }
        }

        /// <summary>
        /// Writes the public key to PEM format
        /// </summary>
        /// <param name="writer"></param>
        public void WritePEM(TextWriter writer)
        {
            var x = new PemWriter(writer);

            var y = this.ExportParameters();

            var z = new RsaKeyParameters(false, new BigInteger(1, y.Modulus), new BigInteger(y.Exponent));

            x.WriteObject(z);
        }
    }
}
